package cn.turboinfo.fuyang.api.gateway.admin.framework.http.interceptor;

import cn.turboinfo.fuyang.api.domain.admin.service.log.OperationLogService;
import cn.turboinfo.fuyang.api.entity.admin.pojo.log.OperationLogCreator;
import cn.turboinfo.fuyang.api.provider.admin.component.session.AdminSessionHelper;
import cn.turboinfo.fuyang.api.provider.admin.framework.shiro.session.AdminSession;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class AdminLogInterceptor implements AsyncHandlerInterceptor {

    private final OperationLogService operationLogService;

    private final AdminSessionHelper sessionHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long sysUserId = (Long) SecurityUtils.getSubject().getPrincipal();
        if (sysUserId != null) {
            AdminSession session = sessionHelper.getSession();
            // 只记录登录用户的行为日志
            String method = request.getMethod();
            String url = request.getRequestURI().substring(request.getContextPath().length());
            String params = convertParamsToString(request.getParameterMap());

            OperationLogCreator creator = OperationLogCreator.builder()
                    .withSysUserId(sysUserId)
                    .withUsername(session.getUsername())
                    .withMethod(method)
                    .withUrl(url)
                    .withParams(params)
                    .build();
            operationLogService.save(creator);
        }
        return true;
    }

    private String convertParamsToString(Map<String, String[]> parameters) {
        StringBuilder sb = new StringBuilder();
        for (String key : parameters.keySet()) {
            String[] values = parameters.get(key);

            StringBuilder subSb = new StringBuilder();
            for (String value1 : values) {
                subSb.append(value1).append("|");
            }
            if (subSb.length() > 0) {
                subSb.deleteCharAt(subSb.length() - 1);
            }
            sb.append(key).append("=").append(subSb.toString()).append("&");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
}
